/*
    10. Write a program in C to append multiple lines at the end of a text file. 

    Assume that the content of the file test.txt is :                                                                       
    test line 1                                                                                                   
    test line 2                                                                                                   
    test line 3                                                                                                   
    test line 4                                                                                                   
    Test Data :
    Input the file name to be opened : test.txt
    Input the number of lines to be written : 3
    The lines are :
    test line 5
    test line 6
    test line 7
    Expected Output :

    The content of the file test.txt is  :                                                                       
    test line 1                                                                                                   
    test line 2                                                                                                   
    test line 3                                                                                                   
    test line 4                                                                                                   
                                                                                                                
    test line 5                                                                                                   
    test line 6                                                                                                   
    test line 7
*/

#include <stdio.h>

#define MAX_STR 1024

int main(void)
{
    char str[MAX_STR];
    char filename[64];
    int lineno, i;
    FILE *fp;
    printf("Input the file name to be opened : ");
    gets(filename);
    printf("Input the number of lines to be written : ");
    scanf("%d", &lineno);
    fflush(stdin);

    fp = fopen(filename, "a"); //"a" 追加到一个文件。写操作向文件末尾追加数据。如果文件不存在，则创建文件。
    if(!fp){
        printf("Open file %s error", filename);
        return -1;
    }

    fputs("\n", fp);
    for(i = 0; i < lineno; i++){
        gets(str);
        fprintf(fp, "%s\n", str);
    }
    fclose(fp);
    fp = fopen(filename, "r");
    printf("The content of file %s is:\n", filename);
    while(fgets(str, MAX_STR, fp)){
        printf("%s", str);
    }

    return 0;
}